<template>
  <div class="pages customer">
    <div class="container_box">
      <div class="tableSearch">
        <el-button v-if="permission==1" type="primary" @click="submitForm('ruleForm')" size="mini">保存</el-button>
        <el-button v-if="permission==0 && setRole('修改')" type="primary" @click="editstatus()" size="mini">修改</el-button>
      </div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :inline="true" label-width="150px" class="system" size="small">
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="启用">
              <el-checkbox :disabled="permission==0" v-model="ruleForm.status"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="启用预付款">
              <el-checkbox :disabled="permission==0" v-model="advanceCharge" @change="handleCheckedChange"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="rowspace" :gutter="40">
          <el-col :span="8">
            <el-form-item label="客户名称:" prop="name">
              <el-input @keyup.native="replace(ruleForm.name,ruleForm, 'name')" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="16" v-model="ruleForm.name"></el-input>
              <span v-else>{{ruleForm.name}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户地址:" prop="address">
              <el-input v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="16" v-model="ruleForm.address"></el-input>
              <span v-else>{{ruleForm.address}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户类型:" prop="shopTypeIds" style='width: 100%' class='shop-type-wrap'>
              <!-- multiple collapse-tags 统一价格需求把多选改成单选-->
              <el-select v-if="permission==1"  v-model="ruleForm.shopTypeIds" @change='handleSelectChange'  placeholder="请选择" size="small" style='width: 178px'>
                <el-option v-for="item in shopTypesList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
              <el-tooltip v-if="permission==0" class="item" effect="dark" :content="ruleForm.shopNames" placement="top-start">
                <span v-if="permission==0" class='shop-type-box'>{{ruleForm.shopNames}}</span>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="rowspace" :gutter="40">
          <el-col :span="8">
            <el-form-item label="统一社会信用代码:" prop="creditCode">
              <el-input @keyup.native="replace(ruleForm.creditCode,ruleForm, 'creditCode')" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3 && ruleForm.auditState != 4 && ruleForm.auditState != 5" maxlength="18" v-model="ruleForm.creditCode"></el-input>
              <span v-else>{{ruleForm.creditCode}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人:" prop="principal">
              <el-input @keyup.native="replace(ruleForm.principal,ruleForm, 'principal')" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="18" v-model="ruleForm.principal" size="small"></el-input>
              <span v-else>{{ruleForm.principal}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人手机号:" prop="linkPhone">
              <el-input @keyup.native="replace(ruleForm.linkPhone,ruleForm, 'linkPhone')" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3 && ruleForm.auditState != 4 && ruleForm.auditState != 5" maxlength="11" v-model="ruleForm.linkPhone"></el-input>
              <span v-else>{{ruleForm.linkPhone}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="rowspace" :gutter="40">
          <el-col :span="8">
            <el-form-item label="邮箱:" prop="email">
              <el-input @keyup.native="replace(ruleForm.email,ruleForm, 'email')" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="30" v-model="ruleForm.email"></el-input>
              <span v-else>{{ruleForm.email}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人身份证号码:" prop="idcardNumber">
              <el-input oninput="value=value.replace(/[^\d|xX]/g,'')" onafterpaste="value=value.replace(/[^\d|xX]/g,'')" maxlength="18" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" v-model="ruleForm.idcardNumber"></el-input>
              <span v-else>{{ruleForm.idcardNumber}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="食品流通许可证号:" prop="foodLicenseNumber">
              <el-input @keyup.native="replace(ruleForm.foodLicenseNumber,ruleForm, 'foodLicenseNumber')" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" v-model="ruleForm.foodLicenseNumber"></el-input>
              <span v-else>{{ruleForm.foodLicenseNumber}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="rowspace" :gutter="40">
          <el-col :span="8">
            <el-form-item class label="注册资金(万元):" prop="registeredCapital">
              <el-input onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" onafterpaste="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="16" v-model="ruleForm.registeredCapital"></el-input>
              <span v-else>{{ruleForm.registeredCapital}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class label="固定电话:" prop="fixPhone">
              <el-input v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="12" v-model="ruleForm.fixPhone"></el-input>
              <span v-else>{{ruleForm.fixPhone}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class label="传真:" prop="fax">
              <el-input oninput="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="16" v-model="ruleForm.fax"></el-input>
              <span v-else>{{ruleForm.fax}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item class label="备注:" prop="remark">
              <el-input v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" type="textarea" :rows="2" v-model="ruleForm.remark"></el-input>
              <span v-else>{{ruleForm.remark}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item class="rowtwo" label="商户LOGO" prop="logoUrl">
              <div class="imgbox">
                <img :src="ruleForm.logoUrl" @click="showimg(ruleForm.logoUrl)" alt>
              </div>
              <el-upload v-if="ruleForm.auditState != 1 && ruleForm.auditState != 3" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                <el-button :disabled="permission == 0" @click="addindex('logoUrl')" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item class="rowtwo" label="营业执照信息" prop="licenseUrl">
              <div class="imgbox">
                <img :src="ruleForm.licenseUrl" @click="showimg(ruleForm.licenseUrl)" alt>
              </div>
              <el-upload v-if="ruleForm.auditState != 1 && ruleForm.auditState != 3" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                <el-button :disabled="permission == 0" @click="addindex('licenseUrl')" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item class="rowtwo" label="食品流通许可证" prop="foodUrl">
              <div class="imgbox">
                <img :src="ruleForm.foodUrl" @click="showimg(ruleForm.foodUrl)" alt>
              </div>
              <el-upload v-if="ruleForm.auditState != 1 && ruleForm.auditState != 3" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                <el-button :disabled="permission == 0" @click="addindex('foodUrl')" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="7">
            <el-form-item class="rowtwo" label="法人身份证正面" prop="idcardFront">
              <div class="imgbox">
                <img :src="ruleForm.idcardFront" @click="showimg(ruleForm.idcardFront)" alt>
              </div>
              <el-upload v-if="ruleForm.auditState != 1 && ruleForm.auditState != 3" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                <el-button :disabled="permission == 0" @click="addindex('idcardFront')" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item class="rowtwo" label="法人身份证反面" prop="idcardReverse">
              <div class="imgbox">
                <img :src="ruleForm.idcardReverse" @click="showimg(ruleForm.idcardReverse)" alt>
              </div>
              <el-upload v-if="ruleForm.auditState != 1 && ruleForm.auditState != 3" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                <el-button :disabled="permission == 0" @click="addindex('idcardReverse')" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script>
import u from "@/util";
import { mapState } from "vuex";
import state from "@/util/state";
import {
  selectBaseShop,
  insertBaseShop,
  uploadFile,
  updateBaseShop,
  getFile,
  selectShopTypeList
} from "@/api";
export default {
  computed: mapState(["power", "merchantId"]),
  data() {
    const validSocialCreditCode = (rule, value, callback) => {
      if (value && !u.validSocialCreditCode(value)) {
        return callback(new Error("格式不正确（18位数字或者大写英文字母）！"));
      } else {
        callback();
      }
    };
    const validEmail = (rule, value, callback) => {
      if (!u.validEmail(value)) {
        return callback(new Error("邮件格式不正确！"));
      } else {
        callback();
      }
    };
    const validTelPhone = (rule, value, callback) => {
      if (value && !u.validTelPhone(value)) {
        return callback(new Error("固定电话格式不正确 "));
      } else {
        callback();
      }
    };
    return {
      advanceCharge: false, // 是否启用预付款
      radio1: "",
      permission: 0, //0:查看,1修改
      area: { province: "", city: "", area: "" },
      labelPosition: "top",
      imgindex: "", //当前上传
      areaIndex: "", // 正在修改的供应商地址
      showErrMsg: false,
      shopTypesList: [], //客户类型列表
      ruleForm: {
        status: true, //启用
        name: "", //门店名称
        address: "", //门店地址
        principal: "", //法人
        creditCode: "", //社会统一信用代码
        registeredCapital: "", //注册资金
        taxesType: "", //纳税人类型
        linkName: "", //联系人
        linkPhone: "", //联系电话
        fixPhone: "", //固定电话
        registeredCapital: "", //注册资金
        fax: "", //传真
        email: "", //邮箱
        remark: "", //备注
        logoUrl: "", //logoUrl
        licenseUrl: "", //营业执照
        foodUrl: "", //食品流通许可证
        idcardFront: "", //身份证正面
        idcardReverse: "", //身份证反面
        shopNames: "", //客户类型名称集合
        shopTypeIds: "", //客户类型id集合
        paymentInitPrice: "", //预付款金额
        enablePayment: 0 //启用预付款   0:未启用   1:启用
      },
      rules: {
        name: [
          { required: true, message: "请输入客户名称", trigger: "blur" },
          { validator: u.checkSpace, trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入客户地址", trigger: "blur" },
          { validator: u.checkSpace, trigger: "blur" }
        ],
        principal: [
          { required: true, message: "请输入法人", trigger: "blur" },
          { validator: u.checkSpace, trigger: "blur" }
        ],
        creditCode: [
          { required: true, message: "统一社会信用代码" },
          { validator: validSocialCreditCode, trigger: "blur" }
        ],
        linkPhone: [
          { required: true, message: "请输入手机号" },
          { validator: u.validatePhone, trigger: "blur" }
        ],
        fixPhone: [{ validator: validTelPhone, trigger: "blur" }],
        licenseUrl: [{ required: true, message: "公司营业执照信息（副本)" }],
        idcardFront: [{ required: true, message: "法人身份证正面电子版" }],
        idcardReverse: [{ required: true, message: "法人身份证反面电子版" }],
        email: [
          { required: true, message: "请填写邮箱" },
          { validator: validEmail, trigger: "blur" }
        ],
        shopTypeIds: [{ required: true, message: "请选择客户类型" }]
      },
      shopTypeIdempty:"",
    };
  },
  created() {},
  mounted() {
    this.permission = u.getQuery("status");
    if (this.permission == 1) {
      this.permission = 1;
      this.id = "";
      this.getShopTypeList();
    } else {
      this.permission = 0;
      this.id = u.getQuery("id");
      this.getdeteils(this.id);
    }
  },
  methods: {
    // 是否启用预付款 监听选中状态
    handleCheckedChange(val) {
      this.ruleForm.enablePayment = val ? 1 : 0;
      console.log(this.ruleForm.enablePayment);
      if (val == true && !this.ruleForm.paymentInitPrice) {
        this.openAdvanceCharge();
      }
    },
    // 填写预付款弹窗
    openAdvanceCharge() {
      this.$prompt("", "预付款初始化金额(元)", {
        confirmButtonText: "保存",
        inputPattern: /^\d+(\.\d+)?$/,
        inputErrorMessage: "金额格式不正确"
      })
        .then(({ value }) => {
          this.ruleForm.paymentInitPrice = value;
        })
        .catch(() => {
          this.advanceCharge = false;
          this.ruleForm.enablePayment = 0;
        });
    },
    replace(value, obj, key) {
      let that = this;
      let event = event || window.event;
      if (event.keyCode == 13) {
        setTimeout(() => {
          that.validItem(value, obj, key);
        }, 100);
      } else {
        that.validItem(value, obj, key);
      }
    },
    validItem(value, obj, key) {
      let res = "";
      switch (key) {
        case "name":
          res = u.replaceChineseAndBracket(value);
          break;
        case "linkName":
        case "principal":
          res = u.replaceChineseAndLetter(value);
          break;
        case "linkPhone":
        case "phone":
        case "mobile":
          res = u.replaceNumber(value);
          break;
        case "landline":
        case "fixPhone":
          res = u.replaceFixPhone(value);
          break;
        case "email":
          res = u.replaceEmail(value);
          break;
        case "creditCode":
        case "idcardNumber":
        case "foodLicenseNumber":
          res = u.replaceSocialCreditCode(value);
          break;
        case "registeredCapital":
          res = u.twoDecimal(value);
          break;
        case "fax":
          res = u.moreThanZero(value);
          break;
      }
      this.$set(obj, key, res);
    },
    //配置权限
    setRole(key) {
      return u.selectTitle(this.power, key);
    },
    //图片大小格式
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片格式错误!");
      }
      if (!isLt2M) {
        this.$message.error("只能上传jpg/png文件，且不超过2M!");
      }
      return isJPG && isLt2M;
    },
    //上传
    uploadSectionFile(param) {
      var fileObj = param.file;
      var data = new FormData();
      data.append("projectName", fileObj.name);
      data.append("file", fileObj);
      uploadFile(data).then(res => {
        if (res.code == 200) {
          let a = `${getFile}?id=${res.data.id}`;
          switch (this.imgindex) {
            case "logoUrl":
              this.ruleForm.logoUrl = a;
              break;
            case "licenseUrl":
              this.ruleForm.licenseUrl = a;
              break;
            case "foodUrl":
              this.ruleForm.foodUrl = a;
              break;
            case "idcardFront":
              this.ruleForm.idcardFront = a;
              break;
            case "idcardReverse":
              this.ruleForm.idcardReverse = a;
              break;
            default:
              break;
          }
        } else {
          this.$message({
            message: "图片上传失败",
            type: "error"
          });
        }
      });
    },
    //区别上传图片
    addindex(i) {
      this.imgindex = i;
    },
    //打开大图
    showimg(url) {
      window.open(url);
    },
    //新建修改
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.ruleForm.customerNature = this.customerNature;
          let postdata = this.ruleForm;
          postdata.shopTypes = "";
          // for (var i = 0; i < postdata.shopTypeIds.length; i++) {
          //   if (i == postdata.shopTypeIds.length - 1) {
          //     postdata.shopTypes += `${postdata.shopTypeIds[i]}`;
          //   } else {
          //     postdata.shopTypes += `${postdata.shopTypeIds[i]},`;
          //   }
          // }
          postdata.shopTypes=postdata.shopTypeIds
          postdata.businessId = this.merchantId;
          postdata.type = 2;
          postdata.source = 4; //2：商户平台门店管理；3：商户平台供应商管理；4：商户平台客户管理'
          postdata.isStore = 1;
          postdata.isTenant = 1;
          if (postdata.status == true) {
            postdata.status = 0;
          } else {
            postdata.status = 1;
          }
          if (this.id != "") {
            this.ruleForm.id = this.id;
            updateBaseShop(postdata).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: "success"
                });
                u.routerTo(
                  "/operate-management/client-management/client-companyMg"
                );
                this.id = "";
              }
            });
          } else {
            insertBaseShop(postdata).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: "success"
                });
                u.routerTo(
                  "/operate-management/client-management/client-companyMg"
                );
              }
            });
          }
        } else {
          this.$message.error("请检查必填信息");
          return false;
        }
      });
    },
    //查看详情
    getdeteils(id) {
      let data = {
        id: id,
        businessId: this.merchantId,
        type: 2
      };
      selectBaseShop(data).then(res => {
        let len = res.data.shopTypeList.length;
        this.ruleForm = res.data;
        this.ruleForm.oldLinkPhone = this.ruleForm.linkPhone; // //商户旧手机号
        this.advanceCharge = this.ruleForm.enablePayment == 0 ? false : true;
        if (res.data.status.toString() == "0") {
          this.ruleForm.status = true;
        } else if (res.data.status.toString() == "1") {
          this.ruleForm.status = false;
        }
        this.status = res.data.status.toString();
        this.ruleForm.shopNames = "";
         for (var i = 0; i < len; i++) {
          if (i == len - 1) {
            this.ruleForm.shopNames += `${res.data.shopTypeList[i].name}`;
          } else {
            this.ruleForm.shopNames += `${res.data.shopTypeList[i].name}、`;
          }
        }
      });
    },
    editstatus() {
      let len = this.ruleForm.shopTypeList.length;
      this.getShopTypeList();
      // let shopTypeIds = [];
       let shopTypeIds = "";
      for (var i = 0; i < len; i++) {
        // shopTypeIds.push(this.ruleForm.shopTypeList[i].id);
        shopTypeIds=this.ruleForm.shopTypeList[i].id
      }
      this.shopTypeIdempty=shopTypeIds
      this.$set(this.ruleForm, "shopTypeIds",shopTypeIds);
      this.permission = 1;
    },
    handleSelectChange(val) {
      // console.log(val);
    },
    getShopTypeList() {
      let that = this;
      let data = {
        shopId: this.merchantId,
        name: "",
        status: 0
      };
      selectShopTypeList(data).then(res => {
        if (res.code == 200) {
          that.shopTypesList = res.data;
          let arr=[]
          that.shopTypesList.forEach(item=>{
            arr.push(item.id)
           })
          let a=arr.includes(this.shopTypeIdempty)
           if(a==false){
             this.$set(this.ruleForm, "shopTypeIds","");
            }
        }
      });
    }
  }
};
</script>
<style>
.distpicker-address-wrapper select {
  height: 32px;
  font-size: 13px;
  padding: 0 0.75rem;
}
</style>
<style scoped lang='less'>
.customer {
  margin: 10px 0;
  background-color: #fff;
}
.container_box {
  padding: 0px 20px;
}
.el-tab-pane .el-row {
  width: 95%;
}
.imgbox {
  width: 180px;
  height: 150px;
  border: 1px dashed #dcdfe6;
}
.imgbox img {
  width: 100%;
  height: 100%;
}
.tableSearch {
  text-align: left;
}
.el-select {
  width: 100%;
}
.shop-type-box {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.el-select-dropdown__item {
  padding-right: 35px;
}
</style>

<style lang="less" scoped>
.customer {
  .el-form-item__label {
    text-align: left;
  }
}
.contact-content {
  width: 100%;
  height: auto;
  margin: 10px auto;
  padding: 10px 0;
  border-top: solid 1px #999;
}

.contact-content .el-select {
  width: 120px;
}

.contact-content .supp-name .el-input {
  width: 150px;
}
.shop-type-wrap {
  .el-form-item__content {
    width: calc(100% - 150px);
  }
}
.span-item {
  margin-right: 30px;
}
</style>
